package com.huluobo.a2202mvvm_im_douyindemo.mvvmDemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.databinding.ActivityMvvmloginDemoBinding;
import com.huluobo.a2202mvvm_im_douyindemo.mvpDemo.UserBean;

/**
 * DataBinding ViewBinding
 * 使用前有个前提,需要打开开关
 * 使用DataBinding,需要将xml转换为一个dataBinding的布局,直接Alt+回车就可以转换
 */
public class MVVMLoginDemoActivity extends AppCompatActivity {
    private ActivityMvvmloginDemoBinding activityMvvmloginDemoBinding;
    private LoginViewModel loginViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //实例化xml布局
        activityMvvmloginDemoBinding = DataBindingUtil.setContentView(this, R.layout.activity_mvvmlogin_demo);

        //实例化ViewModel
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);

        //触发请求
        activityMvvmloginDemoBinding.login.setOnClickListener(v -> {
            loginViewModel.login(
                    activityMvvmloginDemoBinding.username.getText().toString(),
                    activityMvvmloginDemoBinding.password.getText().toString()
            );
        });

        //成功的数据变化,相当于MVP中View里成功的回调
        loginViewModel.success.observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean bean) {
                Toast.makeText(MVVMLoginDemoActivity.this, "登录成功" + bean.getUsername(), Toast.LENGTH_SHORT).show();
            }
        });

        //失败的数据变化
        loginViewModel.failed.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(MVVMLoginDemoActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });

    }
}